<template>
    <div id="subPage">
        <div class="box">
            <div class="top">
                <div class="list">
                    <div class="addBtn" style="width:5rem;display: flex;align-items: center" >
                        <Input v-show="inputShow" @on-search="getSearch" @on-change="getSearch" v-model="keyword" search placeholder="请输入部位名称" style="width: 3.5rem;margin-right: 0.2rem;" clearable/>
                        <Input v-show="inputShow" search placeholder="请输入部位名称" style="opacity:0;position: absolute;top:-9999px;width:1px;" clearable/>
                        <div class="operationBox" v-if="auth.isAdd">
                            <div class="tableBtn" @click="updateRow(0)" >
                                <div class="btnBox">
                                    <div class="text">+  添加部位</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="right" style="display:flex;">
                        <div class="operationBox" v-if="auth.isDownload">
                            <div class="tableBtn" @click="downloadExp" >
                                <div class="btnBox">
                                    <div class="text">下载模板</div>
                                </div>
                            </div>
                        </div>
                        <div class="operationBox" v-if="auth.isExport">
                            <div class="tableBtn">
                                <div class="btnBox" style="position: relative" >
                                    <div class="text">批量导入</div>
                                    <input id="upload_file" type="file" @change="getImportExcelBtn" accept=".xlsx,.xls" style="position: absolute;left:0;top:0;height:100%;opacity: 0; width:100%;"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bottom">
                <div class="tableBox">
                    <div class="tableList" >
                        <el-table ref="table" :height="tableHeight" :data="list" @row-click="changeRow" type='expand' :expand-row-keys="expandKeys" :row-key="getRowKey" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                            <el-table-column label="编码" prop="code"> </el-table-column>
                            <el-table-column label="部位名称" prop="name"> </el-table-column>
                            <el-table-column label="操作" align="center" v-if="auth.isSubordinate||auth.isEdit||auth.isDelete">
                                <template slot-scope="scope">
                                    <el-button v-if="auth.isSubordinate" style="color:#00ACFB;" @click.native.prevent="updateRow(1, scope.row)" type="text" size="small" v-preventReClick="1500">新建下级</el-button>
                                    <el-button v-if="auth.isEdit" style="color:#00ACFB;" @click.native.prevent="updateRow(2, scope.row)" type="text" size="small" v-preventReClick="1500">编辑</el-button>
                                    <el-button v-if="auth.isDelete" style="color:#FF001E" @click.native.prevent="removeRow(scope.row.partId)" type="text" size="small" >删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>

        <Modal class-name="msgModal" v-model="addModal" :title="isAdd?'添加检查部位':'编辑检查部位'" width="520px;" :mask-closable="false" >
            <div class="modal">
                <div class="item">
                    <span class="tip" style="color:red;margin-right:6px;">*</span>
                    <span style="width:80px;">编码 ：</span>
                    <el-input class="inputItem"  oninput="value=value.replace(/^\.+|[^\d.]/g,'')" @blur="salaryChange" maxlength='4' placeholder="请输入编码" style="width: 300px"  v-model="code">
                        <template slot="prepend" v-if="isSonFlag&&parentCode!=null&&parentCode!=''">{{parentCode}}</template>
                    </el-input>
                </div>
                <div class="item" style="align-items: flex-start;">
                    <span class="tip" style="color:red;margin-right:6px;">*</span>
                    <span style="width:80px;">部位名称 ：</span>
                    <Input v-model="name" type="textarea" :maxlength="30" style="width:300px" :autosize="{minRows: 2}" placeholder="请输入部位名称" clearable/>
                </div>
            </div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(1)">取消</div>
                    <div class="button submit" @click="sumbitFn" v-preventReClick="1500">确定</div>
                </div >
            </div>
        </Modal>

        <Modal class-name="msgModal" v-model="delModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(2)">取消</div>
                    <div class="button submit" @click="detele" v-preventReClick="1500">确定</div>
                </div >
            </div>
        </Modal>

        <Modal class-name="msgModal" v-model="ImportModal" title="导入结果" width="600px;" :mask-closable="false">
            <div class="imp">
                <p>
                    <span>成功:</span>
                    <span>{{successNumber}}条</span>
                </p>
                <p>
                    <span>失败:</span>
                    <span>{{failNumber}}条</span>
                </p>
            </div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(3)">取消</div>
                    <div class="button submit" @click="cancel(4)" v-preventReClick="1500">确定</div>
                </div>
            </div>
        </Modal>
    </div>
</template>

<script>
import {
    getQualityPartList,
    qualityPartAdd,
    qualityPartEdit,
    qualityPartDel,
    getImportExcel
} from "@/api/quality";
export default {
    data() {
        return {
            getRowKey(row){
                return row.partId
            },
            expandKeys:[],
            importResultDir:"",
            failNumber:"",
            successNumber:"",
            ImportModal:false,
            fileList:[],
            isAdd:true,
            addModal:false,
            delModal:false,
            removeId:'',
            inputShow:false,
            list:[],
            projectId:"",
            deptName:"",
            pageNum:"",
            current:'',
            name:'',
            code:'',
            pid:"",
            parentCode:"",
            isSonFlag:false,
            keyword:"",
            auth:{
                isAdd:false,
                isDownload: false,
                isExport:false,
                isSubordinate: false,
                isEdit:false,
                isDelete: false,
            },
            btnList:[], //权限列表
            tableHeight: window.innerHeight - 265,
        }
    },
    mounted () {
        this.projectId = this.$store.state.porjectObject.deptId;
        this.deptName = this.$store.state.porjectObject.name;
        this.getAllList()
        this.btnList = JSON.parse(localStorage.getItem("arr"));//localStorage当中的arr项存取的是按钮权限列表
        this.initAuth() //初始化权限
        setTimeout(()=>{
            this.inputShow = true;
        },1)
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        }
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.projectId = val.deptId;
                this.deptName = val.name;
                this.pageNum = 1;
                this.current = 1;
                this.keyword="";
                this.getAllList();
            }
        }
    },
    methods: {
        initAuth(){
            this.auth.isAdd = this.btnList.includes('quality/check/add')
            this.auth.isDownload = this.btnList.includes('quality/check/download')
            this.auth.isExport = this.btnList.includes('quality/check/exportAll')
            this.auth.isSubordinate = this.btnList.includes('quality/check/subordinate')
            this.auth.isEdit = this.btnList.includes('quality/check/edit')
            this.auth.isDelete = this.btnList.includes('quality/check/delete')
        },
        salaryChange(e){
            this.code = e.target.value
        },
        cancel(type){
            this.name = "";
            this.code = "";
            this.pid = "";
            if(type==1){
                this.addModal= false
                this.isAdd=true
                this.isSonFlag=false
            }else if(type==2){
                this.delModal= false
            }else if (type == 3) {
                this.ImportModal = false;
            } else if (type == 4) {
                this.ImportModal = false;
            }
        },
        sumbitFn(){
            if(this.code==''||this.name==''){
                this.$Modal.warning({
                    title: "提示",
                    content: "您有必填项未填写"
                });
                return;
            }
            let reg =  /^[0-9]*$/;
            if(!reg.test(this.code)){
                this.$Modal.warning({
                    title: "提示",
                    content: "编码格式错误"
                });
                return;
            }
            if(this.isAdd){
                let params = {
                    deptId:this.projectId,
                    pid:this.pid,
                    name:this.name,
                    code:this.code,
                }
                qualityPartAdd(params).then((res) => {
                    if (res.code == 200) {
                        this.success();
                    } else {
                        this.$Message.warning(res.msg);
                    }

                }).catch((err) => {
                    console.log(err)
                });

            }else{
                let params = {
                    partId:this.pid,
                    name:this.name,
                    code:this.code,
                }
                qualityPartEdit(params).then((res) => {
                    if (res.code == 200) {
                        this.success();
                    } else {
                        this.$Message.warning(res.msg);
                    }

                }).catch((err) => {
                    console.log(err)
                });
            }

        },
        updateRow(type,row) {
            this.parentCode = "";
            this.name = "";
            this.code = "";
            this.pid = "";
            this.addModal=true
            this.isAdd=true;
            this.isSonFlag=false;
            if(type==1){
                this.pid = row.partId;
                this.parentCode = row.code;
                this.isSonFlag=true;
            }else if(type==2){
                let code =  row.code.split(".")
                let parentCode = '';
                for (let i = 0; i < code.length-1; i++) {
                    parentCode+=code[i]+'.';
                }
                this.pid = row.partId;
                this.name = row.name;
                this.parentCode = parentCode;
                this.code = code[code.length-1];
                this.isAdd=false;
                this.isSonFlag=true;
            }
        },
        downloadExp(){
            // window.open(`${this.$Global.fileSite}/common/质量安全检查部位导入模板.xls`)
            window.open(`http://111.120.11.161:8900/home/workspace/jar/uploads/%E6%A3%80%E6%9F%A5%E9%83%A8%E4%BD%8D%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx`)
        },
        //批量导入
        getImportExcelBtn(e) {
            var file = document.getElementById("upload_file").files[0];
            var formdata = new FormData();
            //文件类型
            var Ary = file.name
                .substring(file.name.lastIndexOf(".") + 1)
                .toLowerCase();
            if (Ary != "xlsx" && Ary != "xls") {
                this.$Modal.warning({
                    title: "提示",
                    content: "请上传正确的文件格式"
                });
                return;
            }
            formdata.append("file", file, file.name);
            formdata.append("deptId", this.projectId);
            let config = {
                headers: { "Content-Type": "multipart/form-data" }
            };
            getImportExcel(formdata, config)
                .then(res => {
                    if (res.code == 200) {
                        this.importResultDir = res.data.importResultDir;
                        this.failNumber = res.data.failNumber;
                        this.successNumber = res.data.successNumber;
                        this.ImportModal = true;
                        document.getElementById("upload_file").value = "";
                        this.getAllList()
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        getAllList() {
            let params ={
                deptId:this.projectId,
                keyword:this.keyword
            }
            getQualityPartList(params)
                .then(res => {
                    if (res.code == 200) {
                        this.expandKeys = [];
                        this.list = res.data.list;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        success() {
            this.$Message.success("操作成功");
            this.name = "";
            this.code = "";
            this.pid = "";
            this.removeid= "";
            this.isAdd=true;
            this.addModal= false
            this.isSonFlag=false;
            this.getAllList();
        },
        detele(){
            qualityPartDel(this.removeid).then((res) => {
                if (res.code == 200) {
                        this.delModal = false;
                        this.success();
                    } else {
                        this.$Message.warning(res.msg);
                    }
            }).catch((err) => {
                console.log(err)
            });
        },
        removeRow(id){
            this.delModal = true;
            this.removeid = id;
        },
        getSearch(){
            this.expandKeys = [];
            // this.collapseAll(this.list, false)
            this.getAllList()
        },
        treeExpand(data) {
            data.forEach(obj => {
                if(obj.name.indexOf(this.keyword)!=-1){
                    this.expandKeys.push(String(obj.partId))
                }
                if (obj.children instanceof Array) {
                    obj.children.forEach(v=>{
                        if(v.name.indexOf(this.keyword)!=-1){
                            this.expandKeys.push(String(obj.partId))
                        }
                    })
                    this.treeExpand(obj.children)
                }
            })
            return data
        },
        collapseAll(arr, isExpand) {
            arr.forEach(i => {
                this.$refs.table.toggleRowExpansion(i, isExpand)
                if (i.children) {
                    this.collapseAll(i.children, isExpand)
                }
            })
        },
        changeRow(row, column, event){
            this.$refs.table.toggleRowExpansion(row)
        }
    }
};
</script>

<style scoped lang="less">
@import "./../../assets/style/themeBase.less";
</style>

<style scoped lang='scss'>
@import "../../assets/style/qualityAndSafety/check.scss";
@import "./../../assets/style/qualityAndSafety/modal.scss";

</style>
